package servlet;

import bean.User;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import dao.impl.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/permissionsServlet")
public class permissionsServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        String method=req.getParameter("method");
        if (method.equals("PermissionFind") ){
            User user=new UserDaoImpl().personnelNum();
            List<User> list=new UserDaoImpl().UserFind();
            req.setAttribute("user",user);
            req.setAttribute("list",list);
            req.getRequestDispatcher("/permissions.jsp").forward(req,resp);
        }else if(method.equals("PermissionUpdateFind")){
            int uid=Integer.parseInt(req.getParameter("uid"));
            System.out.println(uid);
            User user=new UserDaoImpl().UserFindId(uid);
            Gson gson = new Gson();
            String json=gson.toJson(user);
            PrintWriter out=resp.getWriter();
            out.print(json);
            out.flush();
            out.close();
        }else if(method.equals("PermissionUpdate")){
            int uid=Integer.parseInt(req.getParameter("uid"));
            int rights=Integer.parseInt(req.getParameter("rights"));
            int i=new UserDaoImpl().PermissionUpdate(uid,rights);
            PrintWriter out=resp.getWriter();
            out.print(i);
            out.flush();
            out.close();
        }else if(method.equals("PermissionSearch")){
            String uname=req.getParameter("uname");
            if(uname.equals("Search")){
                resp.sendRedirect("permissionsServlet?method=PermissionFind");
            }else {
                List<User> list=new UserDaoImpl().PermissionSearch(uname);
                req.setAttribute("list",list);
                req.getRequestDispatcher("/permissions.jsp").forward(req,resp);
            }
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }


}
